package sg.edu.nus.iss.phoenix.users.controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sg.edu.nus.iss.phoenix.authenticate.delegate.AuthenticateDelegate;
import sg.edu.nus.iss.phoenix.authenticate.entity.Role;
import sg.edu.nus.iss.phoenix.authenticate.entity.User;
import sg.edu.nus.iss.phoenix.core.controller.FCUtilities;
import sg.edu.nus.iss.phoenix.users.delegate.MaintainUsersDelegate;
import sg.edu.nus.iss.phoenix.utils.CommonUtils;

/**
 * Servlet implementation class MaintainUsersController
 *  @author Win Phyo
 */
@WebServlet("/MaintainUsersController/*")
public class MaintainUsersController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MaintainUsersController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("doPost");
		MaintainUsersDelegate maintainUsers= new MaintainUsersDelegate();
		if (FCUtilities.stripPath(request.getPathInfo()).equalsIgnoreCase("create") ) {
			
			//Server side checking
			
			if(request.getParameter("addressLine1").isEmpty() || request.getParameter("city").isEmpty() 
			  ||request.getParameter("country").isEmpty()     || request.getParameter("state") .isEmpty() 
			  ||request.getParameter("zipcode").isEmpty()     || request.getParameter("dob").isEmpty() 
			  ||request.getParameter("name").isEmpty() 
			)	
			{
				setRequireFieldMessage(request);
			}
			else
			{	System.out.println("request.getParameter- insert"+request.getParameter("insert"));
				
				String[] selected = request.getParameterValues("roles");
				ArrayList<Role> roles= new ArrayList<Role>();
				
				for(int i=0 ; i<selected.length; i++)
				{
					Role role = maintainUsers.findRole(Long.parseLong(selected[i]));
					roles.add(role);
					
				}
			
				if(request.getParameter("insert").equalsIgnoreCase("false"))
				{
					updateUser(request, maintainUsers, roles);

				}
				else
				{
					createUser(request, maintainUsers, roles);
				}
				//RequestDispatcher rd = getServletContext().getRequestDispatcher("/pages/setupUser.jsp");
				//rd.forward(request, response);
				
			}
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/pages/setupUser.jsp");
			rd.forward(request, response);
			return;
		}
		
		else if (FCUtilities.stripPath(request.getPathInfo()).equalsIgnoreCase("search") ) 
		{
			System.out.println("Searching..");
			if(request.getParameter("name").isEmpty())
			{
				request.setAttribute("errorMessage", "User Name cannot be empty.");
			}
			else
			{	
				User user = new User();
				user.setName(request.getParameter("name"));
				System.out.println("Search user name is "+request.getParameter("name"));
				user= maintainUsers.findUser(user);
				if(user == null)
				{
					request.setAttribute("errorMessage", "No user found.");
					request.setAttribute("searchUserList",null);
					
				}
				else
				{
					ArrayList<User> userList = new ArrayList<User>();
					userList.add(user);
					request.setAttribute("searchUserList", userList );
				}
			}
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/pages/crudUser.jsp");
			rd.forward(request, response);
			return;
			
		}
		
		else if (FCUtilities.stripPath(request.getPathInfo()).equalsIgnoreCase("update") ) {
			User currentUser = (User) request.getSession().getAttribute("user");
			User user = new User();
			
			if(currentUser != null)
			{
				if(request.getParameter("name").isEmpty() || request.getParameter("name")== null)
				{
					request.setAttribute("errorMessage", "Invalid Parameter");
				}
				else
				{
					user.setName(request.getParameter("name"));
					System.out.println("Modify user name is "+request.getParameter("name"));
					user= maintainUsers.findUser(user);
					if(user == null)
					{
						request.setAttribute("errorMessage", "No user found.");
						request.setAttribute("searchUserList",null);
						
					}
					else
					{

						request.setAttribute("addressLine1", user.getAddressLine1());
						request.setAttribute("addressLine2", user.getAddressLine2());
						request.setAttribute("city", user.getCity());
						request.setAttribute("country", user.getCountry());
						request.setAttribute("state", user.getState());
						request.setAttribute("zipcode", user.getZipCode());
						request.setAttribute("employment_history", user.getEmployment_history());
						request.setAttribute("dob", user.getDob());
						request.setAttribute("name", user.getName());
						request.setAttribute("id", user.getId());
						
						AuthenticateDelegate authenticateDelegate = new AuthenticateDelegate();
						User userRoles =authenticateDelegate.evaluateAccessPreviledge(user);
						request.setAttribute("userRoles", userRoles.getRoles());
						
						request.setAttribute("insert", false);
						System.out.println("Found User");
					}
				}
				
			
			}
			
			else
			{
				setInvalidLoginMessage(request);
			}
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/pages/setupUser.jsp");
			rd.forward(request, response);
			return;
		}
		else if (FCUtilities.stripPath(request.getPathInfo()).equalsIgnoreCase("delete") ) {
			User currentUser = (User) request.getSession().getAttribute("user");
			User user = new User();
			
			if(currentUser != null)
			{
				if(request.getParameter("name").isEmpty() || request.getParameter("name")== null)
				{
					request.setAttribute("errorMessage", "Invalid Parameter");
				}
				else
				{
					user.setName(request.getParameter("name"));
					System.out.println("Modify user name is "+request.getParameter("name"));
					user= maintainUsers.findUser(user);
					if(user == null)
					{
						request.setAttribute("errorMessage", "No user found.");
						request.setAttribute("searchUserList",null);
						
					}
					else
					{

						maintainUsers.deleteUser(user);
						request.setAttribute("errorMessage", "User Account Deleted.");
						
					}
				}
				
			
			}
			else
			{
				setInvalidLoginMessage(request);
			}
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/pages/crudUser.jsp");
			rd.forward(request, response);
			return;
		}
		else if (FCUtilities.stripPath(request.getPathInfo()).equalsIgnoreCase("reset") ) {
			User currentUser = (User) request.getSession().getAttribute("user");
			User user = new User();
			
			if(currentUser != null)
			{
				if(request.getParameter("name").isEmpty() || request.getParameter("name")== null)
				{
					request.setAttribute("errorMessage", "Invalid Parameter");
				}
				else
				{
					user.setName(request.getParameter("name"));
					System.out.println("Modify user name is "+request.getParameter("name"));
					user= maintainUsers.findUser(user);
					if(user == null)
					{
						request.setAttribute("errorMessage", "No user found.");
						request.setAttribute("searchUserList",null);
						
					}
					else
					{
						String randompwd = "123456"; 
						user.setPassword(randompwd);
						maintainUsers.resetPassword(user);
						request.setAttribute("errorMessage", "User Password Reseted to Default password 123456");
						
					}
				}
				
			
			}
			else
			{
				setInvalidLoginMessage(request);
			}
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/pages/crudUser.jsp");
			rd.forward(request, response);
			return;
		}
		else
		{
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/pages/crudUser.jsp");
			rd.forward(request, response);
				
		}
	}

	
	private void createUser(HttpServletRequest request,
			MaintainUsersDelegate maintainUsers ,ArrayList<Role> roles) {
		if(request.getParameter("password").isEmpty()  ||request.getParameter("confirmpassword").isEmpty() )
		{
			request.setAttribute("errorMessage", "Please enter (*) require fields. ");
		}
		if(!request.getParameter("password").trim().equals(request.getParameter("confirmpassword")))
		{
			request.setAttribute("errorMessage", "Password and Confirm Password match.");
		}
		
		User currentUser = (User) request.getSession().getAttribute("user");
		User user = new User();
		
		if(currentUser != null)
		{
			user.setAddressLine1(request.getParameter("addressLine1"));
			user.setAddressLine2(request.getParameter("addressLine2"));
			user.setCity(request.getParameter("city"));
			user.setCountry(request.getParameter("country"));
			user.setCreated_at(CommonUtils.getCurrentDate());
			user.setCreated_by(currentUser.getId());
			user.setDob(CommonUtils.convertStrtoDate(request.getParameter("dob")));
			user.setModified_at(CommonUtils.getCurrentDate());
			user.setModified_by(currentUser.getId());
			user.setName(request.getParameter("name"));
			//user.setEmail(request.getParameter("email"));
			user.setPassword(request.getParameter("password"));
			user.setState(request.getParameter("state"));
			user.setZipCode(request.getParameter("zipcode"));
			user.setEmployment_history(request.getParameter("employment_history"));
			
			User isExistingUser = maintainUsers.findUser(user);
			if(isExistingUser!=null)
			{
				
				maintainUsers.createUser(user);
				user = maintainUsers.findUser(user);
				for(int i=0 ; i < roles.size(); i++)
				{
					 maintainUsers.grantAccess(user, roles.get(i), currentUser);
				}
				
				
				request.setAttribute("errorMessage", "User Save Successfully.");
			}
			else
			{
				request.setAttribute("errorMessage", "Existing User found.User name must be unqiue.");
			}
			
		
		}
		else
		{
			setInvalidLoginMessage(request);
		}
		
		
	}
	
	private void updateUser(HttpServletRequest request,
			MaintainUsersDelegate maintainUsers, ArrayList<Role> roles) {
		
		User currentUser = (User) request.getSession().getAttribute("user");
		User user = new User();
		
		request.setAttribute("insert", "false");
		
		if(currentUser != null)
		{
			
			user.setAddressLine1(request.getParameter("addressLine1"));
			user.setAddressLine2(request.getParameter("addressLine2"));
			user.setCity(request.getParameter("city"));
			user.setCountry(request.getParameter("country"));
			user.setDob(CommonUtils.convertStrtoDate(request.getParameter("dob")));
			user.setModified_at(CommonUtils.getCurrentDate());
			user.setModified_by(currentUser.getId());
			user.setName(request.getParameter("name"));
			//user.setEmail(request.getParameter("email"));
			user.setState(request.getParameter("state"));
			user.setZipCode(request.getParameter("zipcode"));
			user.setEmployment_history(request.getParameter("employment_history"));
			
			User isExistingUser = maintainUsers.findUser(user);
			if(isExistingUser!=null)
			{
				maintainUsers.updateUser(user);
				user = maintainUsers.findUser(user);
				maintainUsers.deleteUserRoles(user.getId());
				for(int i=0 ; i < roles.size(); i++)
				{
					 maintainUsers.grantAccess(user, roles.get(i), currentUser);
				}
				request.setAttribute("errorMessage", "User Update Successfully.");
			}
			else
			{
				request.setAttribute("errorMessage", "Existing User found.User name must be unqiue.");
			}

		}
		else
		{
			setInvalidLoginMessage(request);
		}
		

		
	}
	private void setRequireFieldMessage(HttpServletRequest request) {
		request.setAttribute("errorMessage", "Please enter (*) require fields.");
		request.setAttribute("addressLine1", request.getParameter("addressLine1"));
		request.setAttribute("addressLine2", request.getParameter("addressLine2"));
		request.setAttribute("city", request.getParameter("city"));
		request.setAttribute("country", request.getParameter("country"));
		request.setAttribute("state", request.getParameter("state"));
		request.setAttribute("zipcode", request.getParameter("zipcode"));
		//request.setAttribute("email", request.getParameter("email"));
		request.setAttribute("dob", request.getParameter("dob"));
		request.setAttribute("name", request.getParameter("name"));
		request.setAttribute("insert", request.getParameter("insert"));
		request.setAttribute("employment_history", request.getParameter("employment_history"));
	}

	private void setInvalidLoginMessage(HttpServletRequest request) {
		request.setAttribute("errorMessage", "Invalid login section. Please login first.");
	}


}
